package com.bdqn.petmalldemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.petmalldemo.entity.Cart;
import com.bdqn.petmalldemo.entity.Product;
import com.bdqn.petmalldemo.mapper.CartMapper;
import com.bdqn.petmalldemo.mapper.ProductMapper;
import com.bdqn.petmalldemo.service.CartService;
import com.bdqn.petmalldemo.vo.CartProductVo;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lenovo
 * @since 2020-02-10
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Resource
    private ProductMapper productMapper;

    @Override
    public void addProductToCart(String userId, String productId, Integer quantity) {
        //先根据用户Id,商品Id查询是否存在记录
        QueryWrapper<Cart> cartQueryWrapper  = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id",userId)
                .eq("product_id",productId);
        Cart cart = baseMapper.selectOne(cartQueryWrapper);
        //如果cart不为空,则证明已经存在该商品的记录,则原来的基础上修改数量
        if (null!=cart) {
            cart.setQuantity(cart.getQuantity()+quantity);
            baseMapper.updateById(cart);
        }else{
            //如果不存在,就直接新增一条记录
            cart=new Cart();
            cart.setQuantity(quantity)
                    .setUserId(userId)
                    .setProductId(productId);
            baseMapper.insert(cart);
        }

    }

    @Override
    public List<CartProductVo> getCartProductByUserId(String userId) {
        //先根据当前用户Id查询购物车列表
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id",userId);
        List<Cart> cartList = baseMapper.selectList(cartQueryWrapper);
        //初始化一个返回数据对象
        List<CartProductVo> cartProductVoList = new ArrayList<>();
        //如果当前购物车列表不能为空
        if (!CollectionUtils.isEmpty(cartList)) {
            //进行下一步的数据处理,查询出相关的商品信息
            for (Cart cart:cartList){
                //创建一个返回数据对象
                CartProductVo cartProductVo = new CartProductVo();
                Product product = productMapper.selectById(cart.getProductId());
                cartProductVo.setProduct(product);

                //将购物车相关属性Id,quantity赋值给cartProductVO
                cartProductVo.setId(cart.getId());
                cartProductVo.setQuantity(cart.getQuantity());
                cartProductVo.setProductId(cart.getProductId());

                //将处理过的数据添加到返回对象
                cartProductVoList.add(cartProductVo);
            }
        }

        return cartProductVoList;
    }
}
